package com.xsq.rpc.consumer.start;

import com.xsq.rpc.common.config.CuratorZookeeperProperties;
import com.xsq.rpc.common.config.RpcConfigProperties;
import com.xsq.rpc.common.config.ServerConfig;
import com.xsq.rpc.common.model.RpcMapper;
import com.xsq.rpc.consumer.listener.PathChildrenListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @ClassName ApplicationRunnerTest
 * @Description TODO
 * @Author xsq
 * @Date 2020/5/30 16:40
 * <p>
 * 在springboot 启动的时候进行初始化,在spring注入bean的后面触发的
 * @throws Exception
 */

@Component
@Slf4j
public class ApplicationRunnerTest implements ApplicationRunner {

    private final static Map<String, RpcMapper> rpcMappers = new ConcurrentHashMap<>();

    @Autowired
    private CuratorZookeeperProperties curatorZookeeperProperties;

    @Autowired
    private RpcConfigProperties rpcConfigProperties;

    @Autowired
    private CuratorFramework getCuratorFramework;

    @Autowired
    private ServerConfig serverConfig;


    /**
     * 在springboot 启动的时候进行初始化
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //拉取所有服务端节点信息,监听节点的变化
        getServerNodeInfo();
    }

    /**
     * 拉取所有服务端节点信息,监听节点的变化
     */
    private void getServerNodeInfo() {
        List<String> strings = getChildrenPath(getCuratorFramework, curatorZookeeperProperties.getZkBaseUrl());
        strings.forEach(s -> {
            //获取服务端注册的路径
            try {
                String serverPath = curatorZookeeperProperties.getZkBaseUrl() + "/" + s;
                List<String> urlList = getChildrenPath(getCuratorFramework, serverPath);
                //对服务端节点的子节点进行监听,监听服务端节点的子节点的变化,触发相关的业务逻辑
                PathChildrenListener pathChildrenListener = new PathChildrenListener(getCuratorFramework);
                pathChildrenListener.zkWatch(serverPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    /**
     * 获取该节点下所有子节点的路径
     *
     * @param client
     * @param path
     * @return
     */
    public List<String> getChildrenPath(CuratorFramework client, String path) {
        //获取节点内容
        try {
            return client.getChildren().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

